package com.tech.koufu.ui.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map; 

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.lidroid.xutils.BitmapUtils;
import com.tech.koufu.R; 
import com.tech.koufu.action.RequestQueueSingleton;
import com.tech.koufu.model.TrackerUser;
import com.tech.koufu.tools.CookieStringRequest;
import com.tech.koufu.tools.Statics;
import com.tech.koufu.ui.activity.ExpertsActivity;

import android.content.Context;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView; 
import android.widget.TextView;
import android.widget.Toast;

public class ExpertsShowAdapter extends BaseAdapter {
	private Context context;  
	private LayoutInflater mInflater = null; 
	private int type = 1;
	private BitmapUtils bitmapUtils;
	public ArrayList<TrackerUser> datas;
	private CookieStringRequest stringRequest;
	public String sessionID;
	public String userId;
	public String groupId;
//	public  RequestQueue mQueue; 
	public  ExpertsShowAdapter(Context context,int type,BitmapUtils bitmapUtils, String userid, String groupid) {
		this.context = context;
		this.mInflater = LayoutInflater.from(context);
		this.type = type;
		this.bitmapUtils = bitmapUtils;
		this.userId = userid;
		this.groupId = groupid;
	}

	@Override
	public int getCount() {
		if(datas!=null){
			return datas.size();
		}
		return 0;
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		 ViewHolder holder = null;  
         //如果缓存convertView为空，则需要创建View  
         if(convertView == null)  
         {  
             holder = new ViewHolder();  
             //根据自定义的Item布局加载布局  
             convertView = mInflater.inflate(R.layout.lv_item_experts, parent,false); 
             holder.icon = (ImageView)convertView.findViewById(R.id.iv_head);
             holder.txt_experts_name = (TextView)convertView.findViewById(R.id.txt_experts_name);  
             holder.txt_experts_profit = (TextView)convertView.findViewById(R.id.txt_experts_profit);   
             holder.btn_track = (Button)convertView.findViewById(R.id.btn_track);
             holder.btn_concern = (Button)convertView.findViewById(R.id.btn_concern);
             //将设置好的布局保存到缓存中，并将其设置在Tag里，以便后面方便取出Tag  
             convertView.setTag(holder);  
         }else  
         {  
             holder = (ViewHolder)convertView.getTag();  
         }  
         final TrackerUser tu = datas.get(position);
         holder.txt_experts_name.setText(tu.trackName);
         if(type==1){
        	  SpannableStringBuilder ssb =  new SpannableStringBuilder(String.format(context.getResources().getString(R.string.txt_profitrate_s), tu.zongup));
              ssb.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.bgBlackColor_63)),0,4,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
              holder.txt_experts_profit.setText(ssb);
         }else if(type==3 || type==2){
        	  SpannableStringBuilder ssb =  new SpannableStringBuilder(String.format(context.getResources().getString(R.string.txt_renqi), tu.renqi));
              ssb.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.bgBlackColor_63)),0,3,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
              holder.txt_experts_profit.setText(ssb);
         } 
         
         if(tu.avator!=null){
        	 bitmapUtils.display(holder.icon ,Statics.URL_IMG_CONTECT+ tu.avator);
         }
         final int _pos = position;
        if(type==3){ 
        	holder.btn_track.setText(R.string.btn_cancle_concern);
        	holder.btn_track.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) { 
					removeConcern(tu,_pos);
				}
			});
        }else{
        	final Button btn = holder.btn_track;
        	if(tu.genzong.equals("ready")){
        		holder.btn_track.setOnClickListener(new OnClickListener() { 
    				@Override
    				public void onClick(View v) { 
    					addTrack(tu,btn);
    				}
    			});
        		holder.btn_track.setText(R.string.txt_track);
        		holder.btn_track.setBackgroundResource(R.drawable.btn_track_red);
        	}else{
        		holder.btn_track.setText(R.string.btn_track_experted);
        		holder.btn_track.setBackgroundResource(R.drawable.btn_track_red);
        	}
        	if(tu.guanzhu!=null){
	        	final Button concern = holder.btn_concern;
	        	if(tu.guanzhu.equals("ready")){
	        		holder.btn_concern.setText(R.string.txt_concern); 
	        	}else{
	        		holder.btn_concern.setText(R.string.txt_concerned);
	        	}
	        	holder.btn_concern.setOnClickListener(new OnClickListener() { 
					@Override
					public void onClick(View v) { 
						if(tu.guanzhu.equals("ready")){
							addConcern(tu, concern);
						}else{
							//removeConcern(tu, concern);
						}
					}
				});
        	}
        }
         return convertView;
	}
	private void removeConcern(final TrackerUser tu,final int position){
		String url = Statics.URL_PHP+Statics.IF_removeConcern; 
		stringRequest = new CookieStringRequest(Method.POST, url, new Listener<String>() {

			@Override
			public void onResponse(String response) {   
				if(!TextUtils.isEmpty(response)){
					try {  
//						Log.v("Tt", response);
						JSONObject obj = new JSONObject(response);
						String status = obj.optString("status");
						String data = obj.optString("data");
						Toast.makeText(context, data, Toast.LENGTH_SHORT).show();
						if(status.equals("0")){
							datas.remove(position);
							ExpertsShowAdapter.this.notifyDataSetChanged();
						}
					} catch (JSONException e) { 
						e.printStackTrace();
					}
				} 
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) { 
				
			}
		}){
			@Override
			protected Map<String, String> getParams() throws AuthFailureError { 
				Map<String, String> params = new HashMap<String, String>(); 
				params.put("userID", userId);
				params.put("concern_user_id", tu.trackId);   
				return params;
			}
		}; 
		stringRequest.setHeader(sessionID);
		stringRequest.setTag(ExpertsActivity.TAG);
		RequestQueueSingleton.getInstance(context).addToRequestQueue(stringRequest); 
	}
	/**
	 * 
	* @Title: removeConcern 
	* @Description: 牛人列表中取消关注
	* @param @param tu
	* @param @param position    设定文件 
	* @return void    返回类型 
	* @throws
	 */
	private void removeConcern(final TrackerUser tu,final Button btn){
		String url = Statics.URL_PHP+Statics.IF_removeConcern; 
		stringRequest = new CookieStringRequest(Method.POST, url, new Listener<String>() {

			@Override
			public void onResponse(String response) {   
				if(!TextUtils.isEmpty(response)){
					try {  
						Log.v("Tt_removeConcern", response);
						JSONObject obj = new JSONObject(response);
						String status = obj.optString("status");
						String data = obj.optString("data");
						Toast.makeText(context, data, Toast.LENGTH_SHORT).show();
						if(status.equals("0")){
							btn.setText(R.string.txt_concern); 
							btn.setBackgroundResource(R.drawable.btn_track_red);
						}
						 
					} catch (JSONException e) { 
						e.printStackTrace();
					}
				} 
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) { 
				
			}
		}){
			@Override
			protected Map<String, String> getParams() throws AuthFailureError { 
				Map<String, String> params = new HashMap<String, String>(); 
				params.put("userID", userId);
				params.put("concern_user_id", tu.trackId);   
				return params;
			}
		}; 
		stringRequest.setHeader(sessionID);
		stringRequest.setTag(ExpertsActivity.TAG);
		RequestQueueSingleton.getInstance(context).addToRequestQueue(stringRequest); 
	}
	/**
	 * 
	* @Title: addConcern 
	* @Description:  牛人列表中添加关注
	* @param @param tu
	* @param @param btn    设定文件 
	* @return void    返回类型 
	* @throws
	 */
	private void addConcern(final TrackerUser tu,final Button btn){
		String url = Statics.URL_PHP+Statics.IF_addConcern; 
		stringRequest = new CookieStringRequest(Method.POST, url, new Listener<String>() {

			@Override
			public void onResponse(String response) {   
				if(!TextUtils.isEmpty(response)){
					try {  
//						Log.v("Tt_addConcern", response);
						JSONObject obj = new JSONObject(response);
						String status = obj.optString("status");
						String data = obj.optString("data");
						Toast.makeText(context, data, Toast.LENGTH_SHORT).show();
						if(status.equals("0")){
							btn.setText(R.string.txt_concerned); 
							btn.setClickable(false);
							btn.setBackgroundResource(R.drawable.btn_track_red);
						}
						 
					} catch (JSONException e) { 
						e.printStackTrace();
					}
				} 
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) { 
				
			}
		}){
			@Override
			protected Map<String, String> getParams() throws AuthFailureError { 
				Map<String, String> params = new HashMap<String, String>(); 
				params.put("userID", userId);
				params.put("concern_user_id", tu.trackId);   
				params.put("concern_user_name", tu.trackName); 
				//tracker_gid
				params.put("concerner_gid", tu.trackGid);
				params.put("group_id", groupId);
				params.put("web_id", tu.webId);
				Log.e("Tt",params.toString());
				return params;
			}
		}; 
		stringRequest.setHeader(sessionID);
		stringRequest.setTag(ExpertsActivity.TAG);
		RequestQueueSingleton.getInstance(context).addToRequestQueue(stringRequest); 
	}
	
	
	/**
	 * 
	* @Title: addTrack 
	* @Description: 牛人列表中添加追踪
	* @param @param tu
	* @param @param btn_track    设定文件 
	* @return void    返回类型 
	* @throws
	 */
	private void addTrack( final TrackerUser tu ,final Button btn_track){
		String url = Statics.URL_PHP+Statics.IF_addTrack; 
		stringRequest = new CookieStringRequest(Method.POST, url, new Listener<String>() {

			@Override
			public void onResponse(String response) {   
				if(!TextUtils.isEmpty(response)){
					try {  
//						Log.v("TT-addtrack", response);
						JSONObject obj = new JSONObject(response);
						String status = obj.optString("status");
						String data = obj.optString("data");
						Toast.makeText(context, data, Toast.LENGTH_SHORT).show();
						if(status.equals("0")){
							btn_track.setText(R.string.btn_track_experted);
							btn_track.setClickable(false);
							btn_track.setBackgroundResource(R.drawable.btn_track_red);
						}
					} catch (JSONException e) { 
						e.printStackTrace();
					}
				} 
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) { 
				
			}
		}){
			@Override
			protected Map<String, String> getParams() throws AuthFailureError { 
				Map<String, String> params = new HashMap<String, String>();
				params.put("userID", userId);
				params.put("tracker_id", tu.trackId);
				params.put("tracker_name", tu.trackName);
				//tracker_gid
				params.put("tracker_gid", tu.trackGid);
				params.put("group_id", groupId);
				params.put("web_id", tu.webId);
				return params;
			}
		}; 
		stringRequest.setHeader(sessionID);
		stringRequest.setTag(ExpertsActivity.TAG);
		RequestQueueSingleton.getInstance(context).addToRequestQueue(stringRequest); 
	}
	static class ViewHolder  
    {   
		public ImageView icon;
        public TextView txt_experts_name;  
        public TextView txt_experts_profit;   
        public Button btn_track;
        public Button btn_concern;
        
    }  
}
